'use strict';
module.exports = function (sequelize, DataTypes) {

  var Friendship = sequelize.define('Friendship', {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      primaryKey: true,
      autoIncrement: true
    },
    userId: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false
    },
    friendId: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false
    },
    displayName: {
      type: DataTypes.STRING(41),
      allowNull: false,
      defaultValue: ''
    },
    message: {
      type: DataTypes.STRING(64),
      allowNull: false
    },
    status: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      comment: '10: 请求, 11: 被请求, 20: 同意, 21: 忽略, 30: 被删除'
    },
    timestamp: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      defaultValue: 0,
      comment: '时间戳（版本号）'
    }
  }, {
    classMethods: {
      associate: function (models) {
        Friendship.belongsTo(models.User, {
          foreignKey: 'friendId',
          as: 'user',
          constraints: false
        });
      },
      getInfo: function (userId, friendId) {
        return Friendship.findOne({
          where: {
            userId: userId,
            friendId: friendId
          },
          attributes: ['id', 'status', 'message', 'timestamp', 'updatedAt']
        });
      }
    },
    indexes: [
      {
        unique: true,
        fields: ['userId', 'friendId']
      }, {
        method: 'BTREE',
        fields: ['userId', 'timestamp']
      }
    ],
    tableName: 'friendships'
  });

  return Friendship;
};
